package work.mediway.mdm.biz.dataQuality;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mediway.hos.common.utils.spring.SpringUtils;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.biz.service.biz.SsDataQualityConfigItemService;
import work.mediway.mdm.biz.service.biz.SsDataQualityLogItemService;
import work.mediway.mdm.core.enums.StatusWhetherEnum;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.biz.dto.biz.DataQualityDataExceptionDealDTO;
import work.mediway.mdm.biz.entity.biz.SsDataQualityConfig;
import work.mediway.mdm.biz.entity.biz.SsDataQualityConfigItem;
import work.mediway.mdm.biz.entity.biz.SsDataQualityLogItem;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/8/10
 */
@Slf4j
public class DataQualityDataImportExceptionDealStrategyImpl implements DataQualityDataExceptionDealStrategy {
    @Override
    public void dealDataQualityExceptionValue(DataQualityDataExceptionDealDTO exceptionDealDTO) {
        log.info(exceptionDealDTO.getLogItemId() + ": IMPORT");
        SsDataQualityConfig dataQualityConfig = exceptionDealDTO.getDataQualityConfig();
        SsDataQualityLogItem dataQualityLogItem = SpringUtils.getBean(SsDataQualityLogItemService.class).getById(exceptionDealDTO.getLogItemId());
        List<SsDataQualityConfigItem> dataQualityConfigItems = SpringUtils.getBean(SsDataQualityConfigItemService.class)
                .list(Wrappers.lambdaQuery(SsDataQualityConfigItem.class).eq(SsDataQualityConfigItem::getDataQualityConfigId, dataQualityConfig.getId()));
        if (CollUtil.isNotEmpty(dataQualityConfigItems)) {
            // 唯一值配置
            List<SsDataQualityConfigItem> uniqueItems = dataQualityConfigItems.stream().filter(item -> StrUtil.equals(item.getUniqueFlag(), StatusWhetherEnum.STATUS_Y.getStatusCode())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(uniqueItems)) {
                // 查询源端数据
                String selectSourceSql = StrUtil.strBuilder().append("SELECT *")
                        .append(" FROM ")
                        .append(StrUtil.isBlank(dataQualityConfig.getSourceSchemaName()) ? dataQualityConfig.getSourceTableCode() : dataQualityConfig.getSourceSchemaName() + StrPool.DOT + dataQualityConfig.getSourceTableCode())
                        .append(" WHERE ").append(uniqueItems.get(0).getSourceSystemField()).append(" IN (").append("'").append(dataQualityLogItem.getLogUnique()).append("'").append(" )")
                        .toString();
                // TODO: 2022/10/6
                /*try {
                    Entity query = SqlExecutor.query(SpringUtils.getBean(BaseDatabaseHelper.class).getConnectionByDatabaseId(Long.valueOf(dataQualityConfig.getSourceAccessSystemId()))
                            , selectSourceSql, new EntityHandler());
                    log.info("查询源端数据, 对应SQL为{}", selectSourceSql);
                    if (ObjectUtil.isEmpty(query)) {
                        throw new DataException(StrUtil.format("查询源端数据: {}, 未查询到数据", selectSourceSql));
                    }
                    List<String> key = CollUtil.newArrayList();
                    List<Object> value = CollUtil.newArrayList();
                    for (String k : query.keySet()) {
                        if (ObjectUtil.isNotEmpty(query.get(k))) {
                            key.add(k);
                            value.add("'" + query.get(k) + "'");
                        }
                    }
                    String insertTargetSql = StrUtil.strBuilder().append("INSERT INTO ").append(StrUtil.isBlank(dataQualityConfig.getTargetSchemaName()) ? dataQualityConfig.getTargetTableCode() : dataQualityConfig.getTargetSchemaName() + StrPool.DOT + dataQualityConfig.getTargetTableCode())
                            .append(" ( ").append(StrUtil.join(StrUtil.COMMA, key)).append(" )")
                            .append(" VALUES (").append(StrUtil.join(StrUtil.COMMA, value)).append(" )")
                            .toString();
                    try {
                        log.info("插入数据到目标系统, 对应SQL为: {}", insertTargetSql);
                        SqlExecutor.execute(SpringUtils.getBean(BaseDatabaseHelper.class).getConnectionByDatabaseId(Long.valueOf(dataQualityConfig.getTargetAccessSystemId())), insertTargetSql);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new BizException(StrUtil.format("插入数据到目标系统, 对应SQL为: {}", insertTargetSql), e);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new BizException(StrUtil.format("获取源系统数据, 对应SQL为: {}", selectSourceSql), e);
                }*/
            }
        } else {
            throw new DataException(StrUtil.format("未查询到对应的配置信息, LogItemId = {}", exceptionDealDTO.getLogItemId()));
        }
    }
}
